﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using System.Device.Location;
using Microsoft.Phone.Notification;
using System.Net.NetworkInformation;
using System.Net;
using System.IO;
using System.Text;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;

namespace GPSScheduledTaskAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        //classe per la geo-localizzazione
        private static GeoCoordinateWatcher watcher;

        private static double latitudine;
        private static double longitudine;

        private string IDuser;

        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //update gps
            if (appSettings.Contains("ID"))//se sono loggato
            {
                IDuser = appSettings["ID"].ToString();

                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);/////////
                watcher.Start();/////////////
                GeoCoordinate co = watcher.Position.Location;
                watcher.Stop();////////////////

                latitudine = co.Latitude;
                longitudine= co.Longitude;

                //controllo dati
                if (!(double.IsNaN(latitudine) || double.IsNaN(longitudine)))//sono leggibili
                {
                    //salvo i dati in locale pronti per il DB
                    if (appSettings.Contains("lat"))
                    {
                        appSettings["lat"] = latitudine.ToString().Replace(',', '.');
                        appSettings["lon"] = longitudine.ToString().Replace(',', '.');
                    }
                    else
                    {
                        appSettings.Add("lat", latitudine.ToString().Replace(',', '.'));
                        appSettings.Add("lon", longitudine.ToString().Replace(',', '.'));
                    }

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        //faccio request PHP al DB
                        Uri myDBuri = new Uri("http://www.nearchat.altervista.org/updateGPS.php");
                        HttpWebRequest gpsRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        gpsRequest.Method = "POST";
                        gpsRequest.ContentType = "application/x-www-form-urlencoded";
                        gpsRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), gpsRequest);
                    }            
                }
            }
        }

        void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=4nn!eSupp0rt&user=" + IDuser + "&lat=" + latitudine.ToString().Replace(',', '.') + "&lon=" + longitudine.ToString().Replace(',', '.');
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                //Dispatcher.BeginInvoke(() => ParsingUpdateGPS(result));
            }
        }//GetResponsetStreamCallback
    }
}